package com.quanyan.common.utils;

import com.quanyan.common.encrypt.Coder;
import org.mindrot.jbcrypt.BCrypt;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * 密码加密后存储以及校验.
 *
 * @author songzj
 * @date 16/4/18-18:28
 */
public class PasswordUtil {


    /**
     * More Secure.
     * @param password
     * @return
     */
    public static String encodePasswordWithBCrypt(String password) {
        return Coder.encryptBASE64(BCrypt.hashpw(password, BCrypt.gensalt(8)));
    }

    public static boolean checkPasswordWithBCrypt(String password, String encryptPass) {
        try {
            return BCrypt.checkpw(password, new String(Coder.decryptBASE64(encryptPass), Coder.UTF_8));
        } catch (IOException e) {
        }
        return false;
    }


    /**
     * Advanced Secure
     * @param password
     * @param salt
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static String encodePasswordWithPBEK(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        int iterations = 1000;
        char[] chars = password.toCharArray();
        byte[] saltArr = salt.getBytes();
        PBEKeySpec spec = new PBEKeySpec(chars, saltArr, iterations, 64 * 8);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = skf.generateSecret(spec).getEncoded();
        return  StringUtil.toHex(hash);
    }

    public static boolean checkPassWordWithPBEK(String password, String salt, String encryptPass){
        try {
            String result = encodePasswordWithPBEK(password, salt);
            return result.equals(encryptPass);
        } catch (NoSuchAlgorithmException e) {
        } catch (InvalidKeySpecException e) {
        }
       return false;
    }


}
